import 'package:auto_route/auto_route.dart';
import 'package:base/main.dart';
import 'package:flutter/material.dart';
import 'package:framework/core/base_logic.dart';
import 'package:framework/data/model/function_bean.dart';
import 'package:framework/data/model/menu_bean.dart';
import 'package:framework/main.dart';
import 'package:module_home/pages/home/view_models/function_vm.dart';

class MoreManagerLogic extends BaseLogic {
  FunctionVm functionVM = Get.find<FunctionVm>();

  /// 编辑状态
  final _editState = false.obs;

  bool get isEditing => _editState.value;

  /// 金刚区数据RxList
  final RxList<FunctionBean> functionItems = <FunctionBean>[].obs;

  /// 菜单数据RxList
  final menuCategories = <String, RxList<Datum>>{}.obs;

  @override
  T create<T extends BaseViewModel>() {
    throw UnimplementedError('Unknown VM: $T');
  }

  @override
  void ready() {
    _loadFunctionData();
    _loadMenuData();
  }
  /// 返回按钮
  backButton(BuildContext context) {
    if (isEditing) {
      toggleEditing();
    } else {
      context.router.pop();
    }
  }
  /// 切换编辑状态
  toggleEditing() {
    _editState.toggle();
    _updateFunctionEditValues();
    _updateMenuEditValues();
  }
  /// 保存功能
  save(BuildContext context) {
    functionVM.updateData(functionItems);
    toggleEditing();
    CenterSnackBar.show(context, "保存成功", seconds: 2);
  }
  /// 删除Item数据
  deleteItemData(FunctionBean data) {
    if (_isAddButton(data.name)) {
      toggleEditing();
      return;
    }
    if (!isEditing || functionItems.length <= 1) {
      return;
    }
    functionItems.removeWhere(
        (item) => item.title == data.title && item.name == data.name);
    functionItems.refresh();

    final targetList = menuCategories[data.title!]?.value;
    if (targetList != null) {
      targetList.add(Datum(name: data.name, icon: data.icon, edit: true));
      menuCategories[data.title!]?.value = targetList;
      menuCategories[data.title!]?.refresh();
    }
  }
  /// 添加Item数据
  addItemData(String title, Datum datum) {
    if (!isEditing || datum.name == null) {
      return;
    }
    functionItems.add(FunctionBean(
        title: title, name: datum.name, icon: datum.icon, edit: true));
    functionItems.refresh();

    final targetList = menuCategories[title]?.value;
    if (targetList != null) {
      targetList.remove(datum);
      menuCategories[title]?.value = targetList;
      menuCategories[title]?.refresh();
    }
  }
  /// 恢复默认功能
  restoreDefault() async {
    await Future.wait([
      _getSystemFunctionLists(),
      _loadMenuData(),
    ]);
    functionVM.updateData(functionItems);
    // 恢复未编辑状态
    if (isEditing) {
      toggleEditing();
    } else {
      _addFunctionItemMoreLast();
    }
  }
  /// 拖拽插入item
  insertFunctionItem(int fromIndex, int toIndex) {
    if (fromIndex == toIndex) return;
    final newItems = List<FunctionBean>.from(functionItems);
    final item = newItems.removeAt(fromIndex);
    int finalIndex = toIndex;
    if (toIndex > fromIndex) {
      finalIndex = toIndex - 1;
    }
    finalIndex = finalIndex.clamp(0, newItems.length);
    newItems.insert(finalIndex, item);
    functionItems.value = newItems;
    functionItems.refresh();
  }
  /// 加载金刚区数据
  Future<void> _loadFunctionData() async {
    functionItems.clear();
    final List<FunctionBean>? data = functionVM.functionList;
    functionItems.assignAll(data!);
    _addFunctionItemMoreLast();
  }
  /// 加载菜单的数据
  Future<void> _loadMenuData() async {
    final List<MenuBean>? menuLists = functionVM.menuList;
    menuLists?.forEach((menu) {
      final title = menu.title;
      // 移除菜单列表中金刚区数据
      menu.data.removeWhere((data) {
        final shouldRemove = functionItems.any(
            (element) => element.title == title && element.name == data.name);
        return shouldRemove;
      });
      menuCategories[title] = menu.data.obs;
    });
  }
  /// 获取系统金刚默认数据
  Future<void> _getSystemFunctionLists() async {
    List<FunctionBean>? system = functionVM.systemFunctionList;
    functionItems.clear();
    functionItems.assignAll(system);
  }
  /// 更新金刚区数据状态
  _updateFunctionEditValues() {
    for (var item in functionItems) {
      item.edit = isEditing;
    }
    if (isEditing) {
      functionItems.removeLast();
    } else {
      _addFunctionItemMoreLast();
    }
    functionItems.refresh();
  }
  /// 更新菜单数据状态
  _updateMenuEditValues() {
    menuCategories.forEach((category, rxList) {
      final newList = rxList.map((datum) {
        datum.edit = isEditing;
        return datum;
      }).toList();
      rxList.assignAll(newList);
    });
    menuCategories.refresh();
  }
  /// 金刚区数据默认最后一行添加"更多"按钮
  _addFunctionItemMoreLast() {
    functionItems.add(
      FunctionBean(name: string_add, icon: "icon_add"),
    );
  }
  /// 是否是添加按钮
  bool _isAddButton(String? name) {
    return name == string_add;
  }
}
